package com.example.blog2.controller;

import com.example.blog2.constant.Constants;
import com.example.blog2.model.Result;
import com.example.blog2.model.UserInfo;
import com.example.blog2.service.UserService;
import com.example.blog2.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result login(String username, String password) {
        log.info("用户尝试登录:username:{}, password:{}",username,password);
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            log.error("用户名或密码为空");
            return Result.fail("用户名或密码不能为空");
        }

        UserInfo userInfo = userService.selectByName(username);
        if(userInfo == null) {
            return Result.fail("用户不存在");
        }

        if(!userInfo.getPassword().equals(password)) {
            System.out.println(password);
            System.out.println(userInfo.getPassword());
            return Result.fail("密码错误");
        }

        //密码正确, 返回token
        Map<String, Object> claim = new HashMap<>();
        claim.put(Constants.TOKEN_ID, userInfo.getId());
        claim.put(Constants.TOKEN_USERNAME, userInfo.getUserName());
        String token = JwtUtils.genJwtToken(claim);
        return Result.success(token);
    }
}
